package com.lagou.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Activate(group = {CommonConstants.CONSUMER, CommonConstants.PROVIDER})
public class TPMonitorFilter implements Filter {

    private static final Map<String, List<Long>> requestTime = new ConcurrentHashMap<>();

    public static Map<String, List<Long>> getRequestTime() {
        return requestTime;
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis();
        try {
            // 执行方法
            return invoker.invoke(invocation);
        } finally {
            long time = System.currentTimeMillis() - startTime;
            String interfaceName = getInterfaceName(invocation);
            List<Long> timeList = requestTime.getOrDefault(interfaceName, new ArrayList<>());
            timeList.add(time);
            requestTime.put(interfaceName,timeList);
//            System.out.println("invoke time:" + time + "毫秒");
        }
    }

    public String getInterfaceName(Invocation invocation) {
        return invocation.getServiceName() + ":" + invocation.getMethodName();
    }
}
